$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function (element) {
        element.closest('.form-group').removeClass('has-error').addClass('has-success');
    },
    errorElement: "span",
    errorPlacement: function (error, element) {
        if (element.is(":radio") || element.is(":checkbox")) {
            error.appendTo(element.parent().parent().parent());
        } else {
            error.appendTo(element.parent());
        }
    },
    errorClass: "help-block m-b-none",
    validClass: "help-block m-b-none"
});
$().ready(function () {
	sessionStorage.clear()
	$("#username").focus();
	var validator =$("#loginform").validate({
        errorClass: 'help-block help-block-error', 
        focusInvalid: false,ignore: "",  
        rules: {
            username: {
            	required: true,
                minlength: 2
            },password: {
                required: true,
                minlength: 5
            }
        },messages: {
            username: {
                required: "请输入您的用户名",
                minlength: "用户名必须两个字符以上"
            },password: {
            	required: "请输入您的密码",
                minlength: "密码必须5个字符以上"
            } 
        },highlight: function (element) { 
            $(element).closest('.form-group').addClass('has-error'); 
        },unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error'); 
        },success: function (label) {
            label.closest('.form-group').removeClass('has-error'); 
        },onfocusout: function(element) {
        	$(".msg").html("");
        	$(element).valid(); 
        },onfocusin:function(element){
        	$(".msg").html("");
        }
    });
	 
	var submit = function(){
		if($('#loginform').validate().form()){
			$.ajax({
				data:$('#loginform').serialize(),
				type: "POST",
				url:"../user/login",
				success:function(data){
					if(data.code==0){
						if(window.localStorage){
							sessionStorage.setItem("user", JSON.stringify(data.data)); 
							window.location.href="index.jsp"
						}else{
							alert("浏览器版本过低！请升级浏览器！");
						}
					}else{
						$(".msg").html("<div class='alert alert-danger'>用户名或密码错误！</div>");
						$(".has-error").removeClass("has-error");
						validator.resetForm();
					}
				},error:function(a,b,c){
					$(".msg").html("<div class='alert alert-danger'>系统错误！</div>");
				}
			});
		}
	}
	 
	$("#loginSubmit").bind("click",function(){
		submit();
	});
	$(document).keydown(function(event){ 
		if(event.keyCode==13){ 
			submit();
		}
	});
});
